package org.wisigoth.chat.swing.accountframe;

import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

import org.wisigoth.chat.client.Contact;

public class ContactListCellRenderer extends JPanel implements ListCellRenderer {
	
	private JLabel presenceLabel;
	private JLabel userNameLabel;
	private JLabel avatarLabel;
	
	public ContactListCellRenderer(){
		initComponents();
	}
	
	private void initComponents() {
		this.presenceLabel = new JLabel();
		this.userNameLabel = new JLabel();
		this.avatarLabel = new JLabel();
		this.setLayout(new GridBagLayout());
		
		GridBagConstraints constraintsAvatar = new GridBagConstraints();
		constraintsAvatar.gridx = 0;
		constraintsAvatar.gridy = 0;
		constraintsAvatar.insets.left = 2;
		constraintsAvatar.insets.right = 2;
		constraintsAvatar.fill  = GridBagConstraints.BOTH;
		this.add(this.avatarLabel, constraintsAvatar);
		
		GridBagConstraints constraintsUsername = new GridBagConstraints();
		constraintsUsername.gridx = 1;
		constraintsUsername.gridy = 0;
		constraintsUsername.weightx = 1.0;
		constraintsUsername.anchor = java.awt.GridBagConstraints.WEST;
		this.add(this.userNameLabel, constraintsUsername);
		
		GridBagConstraints constraintsPresence = new GridBagConstraints();
		constraintsPresence.gridx = 2;
		constraintsPresence.gridy = 0;
		//constraintsPresence.weightx = 1.0;
		constraintsPresence.anchor = java.awt.GridBagConstraints.EAST;
		constraintsPresence.fill  = GridBagConstraints.HORIZONTAL;
		this.add(this.presenceLabel, constraintsPresence);
	}

	@Override
	public Component getListCellRendererComponent(JList list, Object value,
			int index, boolean isSelected, boolean cellHasFocus) {
		Contact contact = (Contact)value;
		if(contact == null){
			
			setLabelValues(this.avatarLabel, "", null);
			setLabelValues(this.userNameLabel, "", null);
			setLabelValues(this.presenceLabel, "", null);
		}else{
			//this.avatarLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
			setLabelValues(this.avatarLabel, "", contact.getAvatar().getAvatarImage()); 
			setLabelValues(this.userNameLabel, contact.getUser().getNickName(), null);
			//this.userNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
			//this.userNameLabel.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
			setLabelValues(this.presenceLabel, "", contact.getPresence().getPresenceImage());
		}
		if(isSelected){
			this.setBackground(Color.LIGHT_GRAY);
		}else{
			this.setBackground(Color.WHITE);
		}
		return this;
	}
	
	private static void setLabelValues(JLabel label, String text, Icon icon){
		label.setText(text);
		label.setIcon(icon);
	}

}
